import axios, { AxiosRequestConfig } from 'axios'

const AxiosInstance = axios.create({
  baseURL: import.meta.env.VUE_APP_BASE_API,
  timeout: 100000,
  headers: {
    // 'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
    'Content-type': 'application/json'
  }
})

AxiosInstance.interceptors.request.use(
  config => config,
  error => {
    console.warn(error)
    return Promise.reject(error)
  }
)

AxiosInstance.interceptors.response.use(
  response => {
    const req: XMLHttpRequest = response.request

    /**
     * blob 文件处理
     */
    if (response.data instanceof Blob) {
      const filename = req.getResponseHeader('content-disposition')!.replace('attachment; filename=', '')
      response.data = { data: { blob: response.data, filename } }
      return response
    }

    return response
  },
  error => {
    console.error(error)
    return Promise.reject(error)
  }
)

function request<R = unknown>(config: AxiosRequestConfig) {
  return AxiosInstance.request<ResponseData<R>>(config).then(response => response.data)
}

request.post = function <R = unknown>(url: string, data?: unknown, config?: AxiosRequestConfig) {
  return AxiosInstance.post<ResponseData<R>>(url, data, config).then(response => response.data.data)
}

request.get = function <R = unknown>(url: string, config?: AxiosRequestConfig) {
  return AxiosInstance.get<ResponseData<R>>(url, config).then(response => response.data.data)
}

export default request
